<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-styles/typography.html">
<link rel="import" href="../../bower_components/vaadin-dialog/vaadin-dialog.html">
<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../bower_components/paper-checkbox/paper-checkbox.html">
<link rel="import" href="../../bower_components/paper-radio-group/paper-radio-group.html">
<link rel="import" href="../../bower_components/paper-toggle-button/paper-toggle-button.html">

<dom-module id="schedule-edit-condition">
    <template>
        <style include="shared-styles dialogs">
            .submit-btn {
                background-color: var(--mist-blue);
                color: #fff;
            }

            paper-dialog {
                width: 500px !important;
            }

            paper-button {
                margin: 0 0.29em !important;
            }

            .progress {
                overflow: hidden;
                margin: 0 -24px;
            }
            paper-progress {
                width: 100%;
            }
            paper-progress#progresserror ::slotted(#primaryProgress) {
                background-color: var(--red-color);
            }
            .errormsg-container {
                color: rgba(255,255,255,0.54);
            }
            .errormsg-container iron-icon {
                color: var(--red-color);
                margin: 8px;
            }
            paper-radio-button[checked],
            .background {
                background-color: #eee;
            }
            .background {
                padding: 16px;
                max-height: 310px;
            }
            .overflow-scroll {
                overflow: scroll;
            }
            paper-checkbox {
                display: block;
                font-weight: 500;
                font-size: 16px;
                --paper-checkbox-checked-ink-color: var(--mist-blue) !important;
                --paper-checkbox-checked-color: var(--mist-blue) !important;
            }
        </style>

        <vaadin-dialog id="editScheduleModal" theme="mist-dialog" with-backdrop>
            <template>
                <h2>Edit Schedule Conditions </h2>
                <div class="paper-dialog-scrollable">
                    <div>
                        <paper-radio-group selected="{{isUuidsOrTags}}">
                            <paper-radio-button name="uuids">Specific Machines</paper-radio-button>
                            <paper-radio-button name="tags">Machines with tags</paper-radio-button>
                        </paper-radio-group>
                    </div>
                    <div id="checkboxes" hidden$="{{!isUuids}}" class="background overflow-scroll">
                        <template is="dom-repeat" items="[[_computeMachinesArray(model.machines.*)]]" as="machine">
                            <paper-checkbox name="machinesCheckboxes" checked$="[[_computeIfChecked(machinesIds, machine.id)]]" data-value$="[[machine.id]]" on-change="_updatePayload">[[machine.name]]</paper-checkbox>
                        </template>
                    </div>
                    <div hidden$="{{!isTags}}" class="background">
                        <paper-textarea value="{{tagsString}}"></paper-textarea>
                    </div>
                    <div class="background">
                        <paper-input value="{{machinesAgeDisplayNumber}}" label="If older than" pattern="[0-9]*" errorMessage="Please enter numbers only!" autovalidate></paper-input>
                        <paper-radio-group selected="{{machinesAgeUnit}}">
                            <paper-radio-button name="minutes">minutes</paper-radio-button>
                            <paper-radio-button name="hours">hours</paper-radio-button>
                            <paper-radio-button name="days">days</paper-radio-button>
                        </paper-radio-group>
                    </div>
                    <div class="background">
                        <paper-input value="{{costDisplay}}" label="If it costs more than" pattern="[0-9]*" errorMessage="Please enter numbers only!" autovalidate>
                            <div suffix slot="suffix">[[currency.sign]]/month</div>
                        </paper-input>
                    </div>
                    <div class="progress">
                        <paper-progress id="progress" indeterminate active="{{loading}}" hidden$="[[!loading]]"></paper-progress>
                        <paper-progress id="progresserror" value="100" hidden$="[[!formError]]"></paper-progress>
                        <p class="errormsg-container" hidden$="[[!formError]]"><iron-icon icon="icons:error-outline"></iron-icon><span id="errormsg"></span></p>
                    </div>
                    <div class="clearfix btn-group">
                        <paper-button on-tap="_closeEditScheduleModal">Cancel</paper-button>
                        <paper-button class="blue" disabled$="[[!formReady]]" on-tap="_submitForm">Save</paper-button>
                    </div>
                </div>
            </template>
        </vaadin-dialog>

        <iron-ajax  id="editSchedule"
                    url="/api/v1/schedules/[[schedule.id]]"
                    method="PATCH"
                    loading= "{{loading}}"
                    on-response="_handleResponse"
                    on-error="_handleError"></iron-ajax>
    </template>

    <script>
        (function() {
            'use strict';

            Polymer({
                is: 'schedule-edit-condition',

                properties: {
                    schedule: {
                        type: Object
                    },
                    model: {
                        type: Object
                    },
                    // modelmachines: Array,
                    newSchedule: {
                        type: Object,
                        notify: true
                    },
                    formReady: {
                        type: Boolean,
                        value: false
                    },
                    isUuidsOrTags: {
                        type: String
                    },
                    isUuids: {
                        type: Boolean
                    },
                    isTags: {
                        type: Boolean
                    },
                    loading: {
                        type: Boolean,
                        value: false
                    },
                    formError: {
                        type: Boolean,
                        value: false
                    },
                    conditions: {
                        type: Array
                    },
                    machinesIds: {
                        type: Array,
                        computed: "_computeMachinesIds(schedule.conditions)"
                    },
                    payload: {
                        type: Object,
                        value: {}
                    },
                    tagsString: {
                        type: Array
                    },
                    machinesAge: {
                        type: Number,
                        value: false
                    },
                    machinesCost: {
                        type: Number
                    },
                    costDisplay: {
                        type: String
                    },
                    machinesAgeDisplayNumber: {
                        type: Number
                    },
                    machinesAgeUnit: {
                        type: String
                    },
                    currency: {
                        type: Object
                    }
                },
                observers: [
                    '_computeNewSchedule(schedule.*)',
                    '_isUuidsOrTagsChanged(isUuidsOrTags)',
                    '_updateTagsString(conditions)',
                    '_updateAgeParts(machinesAge)',
                    '_updateCostDisplay(machinesCost)',
                    '_updatePayload(newSchedule.*,isUuidsOrTags,costDisplay,machinesAgeDisplayNumber,machinesAgeUnit)'
                ],
                listeners: {
                    'iron-overlay-closed': '_modalClosed'
                },
                _computeNewSchedule: function(schedule) {
                    if (this.schedule){
                        var newSchedule = {
                            conditions: this.schedule.conditions
                        };
                        this.set('newSchedule', newSchedule);
                        this.set('conditions', this.schedule.conditions);
                        this._computeIsUuidsOrTags(schedule, this.machinesIds);
                    }
                },
                _computeMachinesIds: function(conditions) {
                    console.log('schedule cond', conditions)
                    var ids = [];
                    if (!conditions || !conditions.length || !this._findCondition('machines')){
                        return ids;
                    }
                    else {
                        var cond = conditions.find(function(c){return c.type == "machines"});
                        ids = cond.ids || [];
                    }
                    return ids;
                },
                _findCondition: function(field) {
                    if (this.schedule.conditions && this.schedule.conditions.length){
                        var field = this.schedule.conditions.find(function(con){
                            return ['age', 'machines', 'tags'].indexOf(field) == -1 ? con.field == field : con.type == field;
                        })
                        if (field)
                            return true;
                        return false;
                    }
                    return false;
                },
                _computeIsUuidsOrTags: function(schedule, machinesIds) {
                    if (this.schedule && this.machinesIds && this.machinesIds.length) {
                        this.set('isUuidsOrTags', 'uuids')
                    } else if (this.schedule && this.schedule.tags) {
                        this.set('isUuidsOrTags', 'tags')
                    }
                    console.log('schedule isUuidsOrTags',this.isUuidsOrTags)
                },
                _updateAgeParts: function(age){
                    var machineAge = age && parseInt(age) ? parseInt(age) : '',
                        duration;

                    if (age) {
                        duration = 'minutes';
                    }
                    if (age >= 60 && age%(60) == 0) {
                        duration = 'hours';
                        machineAge = age/60;
                    }
                    if (age >= (60*24) && age%(60*24) == 0 ){
                        machineAge = age/(60*24);
                        duration = 'days';
                    }
                    this.set('machinesAgeDisplayNumber', machineAge);
                    this.set('machinesAgeUnit', duration);
                },
                _updateCostDisplay: function(cost){
                    this.set('costDisplay', !cost || parseFloat(cost) == NaN ? '' : cost);
                },
                _computeMachinesArray: function(machines) {
                    return Object.values(this.model.machines);
                },
                _isUuidsOrTagsChanged: function(isUuidsOrTags) {
                    if (isUuidsOrTags == "uuids"){
                        this.set('isUuids', true);
                        this.set('isTags', false);
                    }
                    else if (isUuidsOrTags == "tags"){
                        this.set('isUuids', false);
                        this.set('isTags', true);
                    }
                    console.log('isUuidsOrTags')
                },
                _openEditScheduleModal: function(e) {
                    this.$.editScheduleModal.opened = true;
                },
                _closeEditScheduleModal: function(e) {
                    this.$.editScheduleModal.opened = false;
                },
                _modalClosed: function(e){
                    if (e.target == this.$.editScheduleModal)
                        this._formReset();
                },
                _submitForm: function(e) {
                    // console.log("payload", this.payload);
                    this.$.editSchedule.body = this.payload;
                    this.$.editSchedule.headers["Content-Type"] = 'application/json';
                    this.$.editSchedule.headers["Csrf-Token"] = CSRF_TOKEN;
                    this.$.editSchedule.generateRequest();
                },
                _formReset: function() {
                    var checkboxes = this.shadowRoot.querySelectorAll('paper-checkbox');
                    Array.prototype.forEach.call(checkboxes, function(c){
                        c.checked = this._computeIfChecked(this.machinesIds, c.dataValue);
                    }.bind(this));
                    this._computeNewSchedule();
                },
                _handleResponse: function(e) {
                    this._closeEditScheduleModal();
                },
                _handleError: function(e) {
                    var message = e.detail.error;
                    if (e.detail.request.statusText)
                        message += " "+e.detail.request.statusText;

                    this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: { msg: message, duration: 5000 } }));
                },
                _updatePayload: function(newSchedule) {
                    console.log('newSchedule', newSchedule);
                    var pl = {},
                        plLength,
                        valid = false;

                    pl["conditions"] = [];

                    console.log('newSchedule uuids', this.isUuids, 'tags', this.isTags);
                    
                    if (this.isUuids){
                        var ids = this._constructCheckboxValue();
                        pl["conditions"].push({type: 'machines', ids: ids});
                        valid = ids.length; 
                    }
                    else if (this.isTags) {
                        var tags = this._constructTagsValue(this.textToArray(this.tagsString));
                        pl["conditions"].push({type: 'tags', tags: tags});
                        valid = this.textToArray(this.tagsString) ? this.textToArray(this.tagsString).length : false;
                    }

                    if (parseInt(this.machinesAgeDisplayNumber) && this.machinesAgeUnit) {
                        var minutes = parseInt(this.machinesAgeDisplayNumber);
                        if (this.machinesAgeUnit == 'hours'){
                            minutes = this.machinesAgeDisplayNumber * 60;
                        }
                        else if (this.machinesAgeUnit == 'days'){
                            minutes = this.machinesAgeDisplayNumber * 60 * 24;
                        }
                        pl["conditions"].push({type: 'age', minutes: minutes});
                    }
                    if (this.costDisplay && this.costDisplay.length && parseFloat(this.costDisplay) != NaN) {
                        pl["conditions"].push({type: 'field', field:'cost__monthly', value: parseFloat(this.costDisplay), operator:'gt'})
                    }
                    this.set('payload', pl);
                    this.set('formReady', valid);
                },
                _computeIfChecked: function(machinesIds, machineId) {
                    if (this.schedule && this.machinesIds)
                        return this.machinesIds.indexOf(machineId) > -1;
                    else
                        return false;
                },
                textToArray: function(str) {
                    if (str) {
                        var arr = [];
                            arr = str.split(',');
                        for (var i = 0; i < arr.length; i++) {
                            arr[i] = arr[i].trim();
                        }
                        return arr;
                    }
                },
                _constructCheckboxValue: function() {
                    var dialog = document.querySelector('vaadin-dialog-overlay'),
                        content = dialog && dialog.shadowRoot.querySelector('#content'),
                        checked = content && content.shadowRoot.querySelectorAll("paper-checkbox[checked]"),
                        arr = [];
                    console.log('checked', checked);
                    if (checked) {
                        for (var i = 0; i < checked.length; i++){
                            arr.push(checked[i].dataset.value);
                        }
                    }
                    return arr;
                },
                _constructTagsValue: function(tagStringsArray) {
                    var arr = {};
                    if (tagStringsArray){
                        tagStringsArray.forEach(function(string){
                            var chunks = string.split("=");
                            if (chunks.length > 0 && chunks[0].trim().length > 0) {
                                var key = chunks[0].trim();
                                arr[key] = "";
                                if (chunks.length > 1)
                                    arr[key] = chunks[1].trim();
                            }
                        });
                    }
                    return arr;
                },
                _updateTagsString: function(conditions){
                    if (this.conditions && this.schedule && this.conditions.length) {
                        var tags = this.conditions.find(function(c){return c.type=="tags"}) ? this.conditions.find(function(c){return c.type=="tags"}).tags : {};
                        var arrTags = Object.keys(tags); 
                        for (var i=0; i < arrTags.length; i++) {
                            var t = arrTags[i];
                            if (tags[t] != null && tags[t].trim() != '') {
                                arrTags[i] = arrTags[i]+'='+tags[t];
                            }
                        }
                        this.set('tagsString', arrTags.toString());
                    }
                }
            });
        })();
    </script>
</dom-module>
